package com.jian.poi.demo.common;

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * Name: WordTableExtractor
 * Description: TODO
 * author: JJ
 * create: 2025/2/19 16:35
 */
public class WordTableExtractor {


    // 读取文档
    public static XWPFDocument loadDocument(String filePath) throws Exception {
        if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
            // 处理 MinIO 的 URL
            try {
                URL url = new URL(filePath);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000); // 设置连接超时为5秒
                connection.setReadTimeout(10000);   // 设置读取超时为10秒

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (InputStream inputStream = connection.getInputStream()) {
                        return new XWPFDocument(inputStream);
                    }
                } else {
                    throw new Exception("无法从 URL 下载文件，HTTP 状态码: " + responseCode);
                }
            } catch (IOException e) {
                throw new Exception("从 URL " + filePath + " 加载文档失败", e);
            }
        } else {
            // 处理本地文件路径
            try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
                return new XWPFDocument(fileInputStream);
            } catch (FileNotFoundException e) {
                throw new Exception("本地文件未找到: " + filePath, e);
            } catch (IOException e) {
                throw new Exception("读取本地文件失败: " + filePath, e);
            }
        }
    }

    /**
     * 获取所有表格
     *
     * @param document
     * @return
     */
    public static List<XWPFTable> getTables(XWPFDocument document) {
        return document.getTables();
    }

    /**
     * 获取基本信息
     *
     * @param tables
     * @return
     * @throws IOException
     */
    public static List<Map<String, Object>> getBaseInfo(List<XWPFTable> tables) throws IOException {
        List<Map<String, Object>> tableDataList = new ArrayList<>();
        // 定义可能的关键字段映射，支持别名
        Map<String, List<String>> keyFieldMap = new HashMap<>();
        keyFieldMap.put("工程名称", Arrays.asList("工程名称"));
        keyFieldMap.put("工程地点", Arrays.asList("工程地点"));
        keyFieldMap.put("施工单位", Arrays.asList("施工单位"));
        keyFieldMap.put("委托单位", Arrays.asList("委托单位"));
        keyFieldMap.put("检测日期", Arrays.asList("检测日期"));
        for (XWPFTable table : tables) {
            List<XWPFTableRow> rows = table.getRows();
            for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
                // 打印当前行信息（行号）
                System.out.println("\n===== 正在处理 第 " + rowIndex + " 行 =====");
                // 表格中的一行
                XWPFTableRow row = rows.get(rowIndex);
                List<XWPFTableCell> cells = row.getTableCells();
                if (cells.get(0).getText().trim().equals("工程名称")) {
                    // 提取当前录像文件的数据块
                    Map<String, Object> tableData = getTableData(rows, rowIndex, table, keyFieldMap);
                    // 只要包含 "管段编号"，就认为是一条有效记录，加入结果集
                    // 判断 tableData 是否包含了 keyFieldMap 中定义的所有必填字段
                    if (keyFieldMap.keySet().stream().allMatch(key -> tableData.containsKey(key))) {
                        // 所有关键字段都有，认为是完整的一条基础信息，添加到结果中
                        tableDataList.add(tableData);
                    }
                }
            }
        }
        return tableDataList;
    }

    /**
     * 获取信息
     *
     * @param tables
     * @return
     * @throws IOException
     */
    public static List<Map<String, Object>> getPipelineDefectInfo(List<XWPFTable> tables) throws IOException {
        List<Map<String, Object>> tableDataList = new ArrayList<>();
        // 定义可能的关键字段映射，支持别名
        Map<String, List<String>> keyFieldMap = new HashMap<>();
        keyFieldMap.put("管段编号", Arrays.asList("管段编号"));
        keyFieldMap.put("水流方向", Arrays.asList("水流方向"));
        keyFieldMap.put("管道材质", Arrays.asList("管道材质"));
        keyFieldMap.put("管道直径", Arrays.asList("管道直径"));
        keyFieldMap.put("视频文件", Arrays.asList("视频文件"));
        keyFieldMap.put("缺陷名称", Arrays.asList("缺陷名称"));
        keyFieldMap.put("检测日期", Arrays.asList("检测日期"));
        keyFieldMap.put("缺陷等级", Arrays.asList("缺陷等级"));
        keyFieldMap.put("缺陷距离", Arrays.asList("缺陷距离"));
        keyFieldMap.put("时钟表示", Arrays.asList("时钟表示"));
        keyFieldMap.put("缺陷长度", Arrays.asList("缺陷长度"));
        keyFieldMap.put("管道埋深", Arrays.asList("管道埋深"));
        keyFieldMap.put("管段长度", Arrays.asList("管段长度"));
        keyFieldMap.put("缺陷描述", Arrays.asList("缺陷描述"));
        keyFieldMap.put("修复建议", Arrays.asList("修复建议"));
        keyFieldMap.put("照片", Arrays.asList("照片"));
        for (XWPFTable table : tables) {
            List<XWPFTableRow> rows = table.getRows();
            for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
                // 打印当前行信息（行号）
                System.out.println("\n===== 正在处理 第 " + rowIndex + " 行 =====");
                // 表格中的一行
                XWPFTableRow row = rows.get(rowIndex);
                List<XWPFTableCell> cells = row.getTableCells();
                if (cells.get(0).getText().trim().equals("管段编号")) {
                    Map<String, Object> tableData = getTableData(rows, rowIndex, table, keyFieldMap);
                    boolean allRequiredFieldsExistExceptPhoto = keyFieldMap.keySet().stream()
                            .filter(key -> !"照片".equals(key))  // 排除 "照片"
                            .allMatch(tableData::containsKey);  // 剩下的 key 必须都在 tableData 中存在
                    // 只要包含 "管段编号"，就认为是一条有效记录，加入结果集
                    if (allRequiredFieldsExistExceptPhoto) {
                        // 所有关键字段都有，认为是完整的一条基础信息，添加到结果中
                        tableDataList.add(tableData);
                    }
                }
            }
        }
        return tableDataList;
    }

    /**
     * 提取信息
     *
     * @param rows
     * @param rowIndex
     * @param keyFieldMap
     * @return
     * @throws IOException
     */
    public static Map<String, Object> getTableData(List<XWPFTableRow> rows, Integer rowIndex, XWPFTable table, Map<String, List<String>> keyFieldMap) throws IOException {
        Map<String, Object> tableData = new LinkedHashMap<>();
        for (int newRollIndex = rowIndex; newRollIndex < rows.size(); newRollIndex++) {
            XWPFTableRow newRow = rows.get(newRollIndex);
            List<XWPFTableCell> newCells = newRow.getTableCells();
            for (int cellIndex = 0; cellIndex < newCells.size() - 1; cellIndex++) {
                // 表格中的一个单元格
                XWPFTableCell cell = newCells.get(cellIndex);
                String cellValue = cell.getText().trim();
                System.out.println("  第 " + cellIndex + " 列单元格内容: [" + cellValue + "]");
                for (Map.Entry<String, List<String>> entry : keyFieldMap.entrySet()) {
                    if (entry.getValue().contains(cellValue)) {
                        //对应的值填充进去
                        String value = newCells.get(cellIndex + 1).getText().trim();
                        System.out.println("   → 取字段 '" + entry.getKey() + "' 的值: '" + value + "'");
                        tableData.put(entry.getKey(), value);
                    }
                    if (keyFieldMap.containsKey("修复建议")) {
                        // 只有存在这个 key 时，才去获取它的 value（List<String>），然后进一步判断
                        List<String> repairSuggestionAliases = keyFieldMap.get("修复建议");
                        if (repairSuggestionAliases != null && repairSuggestionAliases.contains(cellValue)) {
                            System.out.print("符合修复建议\n");
                            //在第0行是第3列
                            int pictureRowIndex = 0;
                            int pictureCellIndex = 2;
                            XWPFTableCell pictureCell = table.getRow(pictureRowIndex).getCell(pictureCellIndex);
                            if (pictureCell != null) {
                                System.out.println("=== 单元格调试信息 ===");
                                System.out.println("单元格文本: " + pictureCell.getText());
                                System.out.println("段落数: " + pictureCell.getParagraphs().size());
                                for (XWPFParagraph paragraph : pictureCell.getParagraphs()) {
                                    for (XWPFRun run : paragraph.getRuns()) {
                                        for (XWPFPicture picture : run.getEmbeddedPictures()) {
                                            System.out.println("提取图片：" + picture.getPictureData());
                                            // 保存图片到本地
                                            byte[] imageData = picture.getPictureData().getData();
                                            if (entry.getValue().contains("照片")) {
                                                //对应的值填充进去
                                                saveImage(tableData, imageData, picture.getPictureData().getFileName());
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            System.out.println("图片不存在");
                        }
                    }
                }
            }
        }
        return tableData;
    }

    /**
     * 获取所有表格数据
     *
     * @param tables
     * @return
     */
    public static List<Map<String, Object>> getTableData(List<XWPFTable> tables) throws IOException {
        List<Map<String, Object>> tableData = new ArrayList<>();
        for (XWPFTable table : tables) {
            List<XWPFTableRow> rows = table.getRows();
            for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
                // 表格中的一行
                XWPFTableRow row = rows.get(rowIndex);
                // 打印当前行信息（行号）
                System.out.println("\n===== 正在处理 第 " + rowIndex + " 行 =====");
                List<XWPFTableCell> cells = row.getTableCells();
                for (int cellIndex = 0; cellIndex < cells.size(); cellIndex++) {
                    // 表格中的一个单元格
                    XWPFTableCell cell = cells.get(cellIndex);
                    System.out.println("  第 " + cellIndex + " 列单元格内容: [" + cell.getText().trim() + "]");
                }
            }
        }
        return tableData;
    }


    // 保存照片到文件
    private static void saveImage(Map<String, Object> map, byte[] imageData, String imageName) throws IOException {
        Path imagePath = Paths.get("./uploads/images/" + imageName);
        Files.createDirectories(imagePath.getParent());
        Files.write(imagePath, imageData);
        System.out.println("图片保存为:./uploads/images/");
        Map<String,Object> imageBaseInfo = new HashMap();
        imageBaseInfo.put("照片id",1);
        imageBaseInfo.put("照片地址",imagePath.getParent().toString() + imageName);
        map.put("照片", imageBaseInfo);

    }
}
